<?php

namespace App\Http\Controllers\Api\Wechat;

use App\Http\Controllers\Api\V1\BaseController;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Tymon\JWTAuth\Facades\JWTAuth;
use EasyWeChat\Factory;
use App\Models\User;

class LoginController extends BaseController
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */

    public function login(Request $request)
    {

        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if (method_exists($this, 'hasTooManyLoginAttempts') &&
            $this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }


        $request->offsetSet('status', 1);
       // if ($this->attemptLogin($request)) {
        if ($token = $this->guard()->attempt($this->credentials($request))) {
            $request->offsetSet('token', $token);

            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username()
    {
        return 'name';
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard("api");
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request)
    {

        $token = $request->offsetGet('token');

        $this->clearLoginAttempts($request);

        $config = config('wechat.mini_program.default');

        $app = Factory::miniProgram($config);

        $code = $request->input('code');

        if ($code) {

            $wechatuser = $app->auth->session($code);

            if (!isset($wechatuser['errcode']) || !$wechatuser['errcode']) {
                $user = User::where('name', $request->name)->first();

                $user->openid = $wechatuser['openid'];
                $user->save();

                return $this->json([
                    'access_token' => $token,
                    'token_type' => 'bearer',
                    'expires_in' => JWTAuth::factory()->getTTL() * 60
                ]);

            } else {

                Log::error('wechatmini get session error');
                Log::error($wechatuser);

                return $this->json([], '获取微信用户信息失败, code:'. $wechatuser['errcode'], 30040);
            }


        } else {
            Log::error('code is empty');

            return $this->json([], '微信请求未携带code', 30050);
        }

    }

}
